<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/9/18
 * Time: 15:10
 */

namespace app\admin\controller;


use app\admin\model\ApiResponse;
use app\admin\lib\AdminController;
use app\common\model\curriculum\CurriculumVideo;
use app\common\model\exam\Questions;
use app\common\model\exam\QuestionsClass;
use think\Db;
use think\Exception;
use think\Log;

class Exam extends AdminController
{

    /**
     * 获取分类列表
     *
     * @return ApiResponse
     */
    public function class_list() {

        $form = $this->getAndCheckForm([
            ['parent', 'integer',],
        ]);

        $re = Db::table('questions_class')
            ->where('class_parent','=', intval($form['parent']??0))
            ->select();

        return ApiResponse::success($re);
    }


    /**
     * 保存分类
     *
     * @return ApiResponse
     */
    public function class_save() {

        $form = $this->getAndCheckForm([
            ['class_name','require',],
            ['class_sort','require|integer',],
        ]);

        $class_id = intval($form['class_id'] ?? 0);
        if ($class_id > 0) {
            QuestionsClass::update($form);
        } else {
            QuestionsClass::create($form);
        }
        QuestionsClass::cacheTree(true);

        return ApiResponse::success();
    }


    /**
     * 删除分类
     *
     * @return ApiResponse
     */
    public function class_del() {

        $form = $this->getAndCheckForm([
            ['id','require|integer',],
        ]);

        QuestionsClass::destroy($form['id']);
        QuestionsClass::cacheTree(true);

        return ApiResponse::success();
    }

    /**
     * 分类树
     * @return ApiResponse
     */
    public function class_tree() {

        $t = QuestionsClass::cacheTree();

        return ApiResponse::success($t);
    }

    public function exam_get() {
        $form = $this->getAndCheckForm([
            ['video_id','require',],
        ]);
        $re = Db::table('curriculum_exam')->where('exam_video','=', $form['video_id'])->find();
        return ApiResponse::success($re);
    }

    public function exam_save() {
        $form = $this->getAndCheckForm([
            ['video_id','require|integer',],
            ['exam_duration','require|integer',],
        ]);

        $v = CurriculumVideo::get($form['video_id']);
        $exam = Db::table('curriculum_exam')->where('exam_video','=', $v->video_id)->find();
        if (empty($exam)) {
            $exam_id = Db::table('curriculum_exam')->insert([
                'exam_curriculum' => $v->video_curriculum,
                'exam_video' => $v->video_id,
                'exam_level' => $v->video_level,
                'exam_duration' => $form['exam_duration'],
            ],false,true);
        } else {
            $exam_id = $exam['exam_id'];
            Db::table('curriculum_exam')->where('exam_id','=', $exam_id)->update([
                'exam_duration' => $form['exam_duration'],
            ]);
        }

        return ApiResponse::success(['exam_id' => $exam_id,'exam_duration'=>$form['exam_duration']]);
    }

    /**
     * 题库列表
     *
     * @return array
     */
    public function questions_list() {

        $form = $this->getAndCheckForm([
            ['exam_id', 'require|integer',],
            ['class_id', 'integer',],
            ['rows', 'integer',],
            ['page', 'integer',],
        ]);

        $query = Db::table('questions q');

        // 视频关联
        $query->join('curriculum_exam_questions eq','eq.eq_questions=q.questions_id');
        $query->where('eq.eq_exam','=', $form['exam_id']);

        // 分类
        $query->join('questions_class c','c.class_id=q.questions_class_child');
        if ( ($class_id = intval($form['class_id'] ?? 0)) > 0) {
            $query->where('q.questions_class_child','=', $class_id);
        }
        $query->order('q.questions_id','desc');

        $re = $query->paginate($form['rows']??10, false, [
            'page' => $form['page'] ?? 1,
        ])->toArray();
        $re['code'] = 200;

        return $re;
    }

    /**
     * 保存题目
     * @return ApiResponse
     */
    public function questions_save() {
        $rule = [
            ['questions_class_child','require','分类不能为空'],
            ['questions_title','require','标题不能为空'],
            ['questions_content','require','内容不能为空'],
            ['questions_option','require','选项不能为空'],
            ['questions_answer','require','答案不能为空'],
            ['questions_scores','require','分数不能为空'],
            ['questions_type','require','题型不能为空'],
            ['option_content_type','require','选项类型不能为空'],
            ['exam_id','require|integer','视频id不能为空'],
        ];
        $form = $this->getAndCheckForm($rule);
        $questions_id = intval($form['questions_id'] ?? 0);

        $exam_id = intval($form['exam_id']);
        $data = [];
        foreach ($rule as $item) {
            $data[$item[0]] = $form[$item[0]];
        }
        unset($data['exam_id']);

        try{
            Db::startTrans();

            $class = QuestionsClass::get($form['questions_class_child']);
            $data['questions_class_parent'] = $class->class_parent;

            if ($questions_id > 0) {
                $data['questions_id'] = $questions_id;
                $data['questions_updatetime'] = time();
                Questions::update($data);
            } else {
                $data['questions_addtime'] = time();
                $q = Questions::create($data);
                Db::table('curriculum_exam_questions')->insert([
                    'eq_exam' => $exam_id,
                    'eq_questions' => $q->questions_id,
                ]);
            }

            Db::commit();
            return ApiResponse::success();
        }catch (Exception $ex){
            Db::rollback();
            Log::error($ex->getMessage());
            return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'保存失败');
        }

    }

    /**
     * 删除题目
     *
     * @return ApiResponse
     */
    public function questions_del() {
        $id = intval(input('post.id'));
        if ($id > 0) {
            Questions::destroy($id);
            Db::table('curriculum_exam_questions')->where('eq_questions','=', $id)->delete();
        }
        return ApiResponse::success();
    }


}